﻿using System;
using SilverlightDatabase.Server;
using SilverlightDatabase;

namespace SilverlightDatabaseTest
{
    public class DatabaseProcessor : IDatabaseProcessor
    {
        #region IDatabaseProcessor Members

        public bool PutDatabase(SilverlightDatabase.Database database)
        {
            if (database.Table<Person>().Count == 20 && database.Table<Phone>().Count == 10)
            {
                return true;
            }
            return false;
        }

        public SilverlightDatabase.Database GetDatabase(string databaseName, string password, bool useCompression)
        {
            
            Database db = Database.CreateDatabase(databaseName, password, useCompression, true);
            db.CreateTable<Person>();

            if (db.Table<Person>() != null)
            {
                for (int i = 0; i < 20; i++)
                {
                    db.Table<Person>().Add(NewRandomPerson());
                }
            }

            db.CreateTable<Phone>();

            if (db.Table<Phone>() != null)
            {
                for (int i = 0; i < 10; i++)
                {
                    db.Table<Phone>().Add(NewRandomPhone());
                }
            }
            return db;
        }

        public SilverlightDatabase.Database UpdateDatabase(SilverlightDatabase.Database database)
        {
            Database db = Database.CreateDatabase(database.DatabaseName, database.Password, database.UseCompression, true);
            db.CreateTable<Person>();

            if (db.Table<Person>() != null)
            {
                for (int i = 0; i < 4; i++)
                {
                    db.Table<Person>().Add(NewRandomPerson());
                }
            }

            db.CreateTable<Phone>();

            if (db.Table<Phone>() != null)
            {
                for (int i = 0; i < 2; i++)
                {
                    db.Table<Phone>().Add(NewRandomPhone());
                }
            }
            return db;
        }

        private Person NewRandomPerson()
        {
            Random rand = new Random();
            return new Person() { FirstName = "John " + rand.Next(), LastName = "Doe " + rand.Next(), Salary = rand.Next(), BirthDate = new DateTime(1900 + rand.Next(1, 99), 1, 1) };
        }

        private Phone NewRandomPhone()
        {
            Random rand = new Random();
            return new Phone() { PhoneNumber = rand.Next().ToString(), Extension = rand.Next().ToString() };
        }


        #endregion

    }
}
